package com.zkingsoft.plugin.util;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 钉钉机器人工具
 * 
 * @author 李广林
 * @email 935090232@qq.com
 * @date 2018年5月9日
 */
public class DingDingRobotUtil {

	/**
	 * 发送text类型的消息
	 * 
	 * @author admin
	 * @email 935090232@qq.com
	 * @date 2018年6月11日
	 * @param dingdingRobotToken
	 * @param content
	 * @param atMobile
	 */
	public static void sendText(String dingdingRobotToken, String content, String atMobile) {
		String at = "";
		if (atMobile != null) {
			at = "\"at\":{\"atMobiles\":\"[" + atMobile + "]\"   , \"isAtAll\": false}";
		}
		content = content.replace("\"", "\\\"");
		String textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\":\"" + content + "\"}   ," + at + "}";
		sendMsg(dingdingRobotToken, textMsg);
	}

	/**
	 * 发送链接消息
	 * 
	 * @author admin
	 * @email 935090232@qq.com
	 * @date 2018年6月11日
	 * @param dingdingRobotToken
	 * @param content
	 * @param title
	 * @param picUrl
	 * @param messageUrl
	 */
	public static void sendLink(String dingdingRobotToken, String content, String title, String picUrl,
			String messageUrl) {
		content = content.replace("\"", "\\\"");
		String textMsg = "{ \"msgtype\": \"link\", \"link\": {\"text\":\"" + content + "\" , \"title\":\"" + title
				+ "\" , \"picUrl\":\"" + picUrl + "\" , \"messageUrl\":\"" + messageUrl + "\"  }   }";
		sendMsg(dingdingRobotToken, textMsg);
	}

	private static void sendMsg(String dingdingRobotToken, String content) {
		HttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(dingdingRobotToken);
		httppost.addHeader("Content-Type", "application/json; charset=utf-8");
		StringEntity se = new StringEntity(content, "utf-8");
		httppost.setEntity(se);
		HttpResponse response;
		try {
			response = httpclient.execute(httppost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String result = EntityUtils.toString(response.getEntity(), "utf-8");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

}
